package com.zxy.car.config;
//张鑫宇专用可粘贴：定时同步

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.car.entity.RecordEntity;
import com.zxy.car.service.RecordService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SpringTaskConfig {

    @Autowired
    private RecordService recordService;

    @SuppressWarnings("all")
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void upAllShop(){
        try {
            QueryWrapper<RecordEntity> wrapper = new QueryWrapper<>();

            List<RecordEntity> list = recordService.list(wrapper);
            if (list.size() > 0) {
                System.out.println("需要执行------------");
                //同步es list是需要同步的数据
                BulkRequest bulkRequest = new BulkRequest();
                for (RecordEntity recordEntity : list) {
                    IndexRequest request = new IndexRequest("payrecord");
                    request.id(recordEntity.getId().toString());
                    String jsonString = JSONObject.toJSONString(recordEntity);
                    request.source(jsonString, XContentType.JSON);
                    bulkRequest.add(request);
                }
                restHighLevelClient.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
                List<RecordEntity> collect = list.stream().map(item -> {

                    return item;
                }).collect(Collectors.toList());
                recordService.updateBatchById(collect);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
